import 'dart:io';

class CommonUtils {
  static String removeDecimalZeroFormat(double n) {
    return n.toStringAsFixed(n.truncateToDouble() == n ? 0 : 1);
  }

  ///格式化文件大小
  ///```
  ///@param bytes 字节数 20 * 1024 * 1024
  ///@param fractionDigits 保留小数位数
  ///@return 格式化字符串 "20M"
  ///```
  static String renderFileSize(double? bytes, {int fractionDigits = 0}) {
    if (bytes == null) {
      return "";
    }
    List<String> unitArr = []
      ..add('B')
      ..add('K')
      ..add('M')
      ..add('G');
    int index = 0;
    while (bytes! > 1024) {
      index++;
      bytes = bytes / 1024;
    }
    String size = bytes.toStringAsFixed(fractionDigits);
    return size + unitArr[index];
  }

  ///删除目录及子目录中的文件
  ///
  static Future<void> deleteDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
          await deleteDir(child);
        }
      }
      await file.delete();
    } catch (e) {
      print(e);
      return Future.error(e);
    }
  }

  ///计算目录中所有文件的总字节数
  ///
  static Future<int> calcSizeOfFilesInDir(final FileSystemEntity file) async {
    try {
      if (file is File) {
        int length = await file.length();
        return length;
      }
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        int total = 0;
        for (final FileSystemEntity child in children)
          total += await calcSizeOfFilesInDir(child);
        return total;
      }
      return 0;
    } catch (e) {
      print(e);
      return Future.error(e);
    }
  }
}
